#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
1. 寻找大单
    |
2. 开仓(高出或低于大单一个价位，限价买入或卖出币)
    |
3. 监听开仓订单完成 & 监听大单动向
    |
4. 创建网格挂单                         大单消失
    |                                   |
5. 监听大单动向 & 所有挂单动向              |
    |                                   |
    --------------------                |
    |                   |               |
5. 大单消失       所有挂单交易完成          |
    |                   |               |
6.  取消所有挂单,          |           <--|
   市价卖出或买入所有币    |  
        |               |
         ---------------
                |
            重新第1步
"""

from gate_api import ApiClient, Configuration, SpotApi, Order
import time
import futures_toolbox

# class status:
#     Rea= 1
#     g = 2
#     c = 3


class YYFollowingLargeOrder:
    def __init__(
            self,
            apiKey,
            apiSecret,
            contract,
            singleAmount,
            totalValue,
            interval
            ):
        self.__settle = "usdt"  # 市场
        self.__apiKey = apiKey
        self.__apiSecret = apiSecret
        self.__hostUsed = 'https://api.gateio.ws/api/v4'
        self.__contract = contract # 交易对
        self.__singleAmount = singleAmount #网格单笔交易量
        self.__interval = interval # 深度
        self.__totalValue = totalValue # 开仓总价值

        self.__bigOrderPrice = 0.0 # 大单价格
        print('⭕️ init：%f' % self.__bigOrderPrice)
        # API管理工具
        config = Configuration(key=apiKey, secret=apiSecret, host=self.__hostUsed)
        spot_api = SpotApi(ApiClient(config))
        self.__spot_api = spot_api

        


    def fundLargeOrder(self):
        """1.寻找大单
        """
        print('寻找大单')
        # 1. 获取百分比深度 eg.'0.01'

        list_order = self.__spot_api.list_order_book(
            self.__contract,
            interval=self.__interval
        )
        asks = list_order.asks
        bids = list_order.bids

        ### 计算平均值 ###

        # 总卖量
        asks_amount = 0.0
        # 深度列表卖方价格数量
        asks_list_count = len(asks)
        # 卖方平均量
        average_asks_amount = 0.0
        for item in asks:
            amount = float(item[1])
            asks_amount = asks_amount + amount
            # print('%s : %f' % (item[0] ,amount))
        # print(bids_amount)
        average_asks_amount = asks_amount / asks_list_count
        print('✅✅ %s ✅ 卖方 平均：%f' % (self.__contract, average_asks_amount))

        # 总买量
        bids_amount = 0.0
        # 深度列表买方价格数量
        bids_list_count = len(bids)
        # 买方平均量
        average_bids_amount = 0.0
        for item in bids:
            amount = float(item[1])
            bids_amount = bids_amount + amount
            # print('%s : %f' % (item[0] ,amount))
        # print(bids_amount)
        average_bids_amount = bids_amount / bids_list_count
        print('✅✅ %s ✅ 买方 平均：%f' % (self.__contract, average_bids_amount))

         
        ### 寻找大单 ###
        # 寻找卖方大单
        # for item in asks:
        #     amount = float(item[1])
        #     rate = amount / average_asks_amount
        #     price = item[0]
        #     print('%s : %f' % (price, rate))
        #     if rate > 5:
        #         print('⭕️⭕️⭕️%s : %f' % (price, rate))
        #         futures_toolbox.playVoice('audiomixing.mp3')
        #         break

        # print('---------')

        # 寻找买方大单
        for item in bids:
            amount = float(item[1])
            rate = amount / average_bids_amount
            price = item[0]
            print('%s : %f' % (price, rate))
            if rate > 5:
                print('⭕️⭕️⭕️%s : %f' % (price, rate))
                futures_toolbox.playVoice('audiomixing.mp3')
                self.__bigOrderPrice = float(price)
                break
        print('========================================================================')
    
    def openAPosition(self, amount):
        """2.开仓(高出或低于大单一个价位，限价买入或卖出币)
        :param str amount: 交易数量 (required)
        """

        # FIXME 测试数据
        self.__bigOrderPrice = "7.61"
        # ****************


        open_position_price = self.__bigOrderPrice + float(self.__interval)
        print('大单：%f' % self.__bigOrderPrice)
        price = str(open_position_price)
        order = Order(currency_pair='GT_USDT',type='limit',side='buy',price=price,amount=amount)
        o = self.__spot_api.create_order(order)
        print('✅ 交易:%s' % o)


    def addObserveForInitPositionorder(self):
        """3.监听开仓订单完成
        """

    def makeWangGeOrder(self):
        """创建网格挂单
        """

def main():
    print('进来了')

    # 主账户
    # following = YYFollowingLargeOrder(
    #     'a8c715a17b856dda7d3440059ca05e42',
    #     '0a89a221048767617351b3803c9a15bf0892c28f8892e1445a7ef2470427cfac',
    #     'GT_USDT',
    #     3,
    #     100,
    #     '0.01'
    # )
    # 子账户
    following = YYFollowingLargeOrder(
        '20b8579b7127df82fef8acaee74d80ec',
        'df4fd255885fc04001aef012b0cb6263ea5ae95ba2e00acfbdc7b5fcc30844c3',
        'GT_USDT',
        3,
        100,
        '0.01'
    )
    # following2 = YYFollowingLargeOrder(
    #     'a8c715a17b856dda7d3440059ca05e42',
    #     '0a89a221048767617351b3803c9a15bf0892c28f8892e1445a7ef2470427cfac',
    #     'POGAI_USDT',
    #     200000,
    #     100,
    #     '0.0000001'
    # )
    # following3 = YYFollowingLargeOrder(
    #     'a8c715a17b856dda7d3440059ca05e42',
    #     '0a89a221048767617351b3803c9a15bf0892c28f8892e1445a7ef2470427cfac',
    #     'BNB_USDT',
    #     0.03,
    #     100,
    #     '1'
    # )
    # following4 = YYFollowingLargeOrder(
    #     'a8c715a17b856dda7d3440059ca05e42',
    #     '0a89a221048767617351b3803c9a15bf0892c28f8892e1445a7ef2470427cfac',
    #     'BONK_USDT',
    #     0.03,
    #     100,
    #     '0.0000001'
    # )
    
    # following.openAPosition(1)
    while 1:
        
        following.fundLargeOrder()
        # following4.fundLargeOrder()
        time.sleep(1)


if __name__ == '__main__':
    main()